<template>
	<view class="sing">
		<view class="sinup_top">
			<view class="acname">
				<view class="acname_l">
					项目名称
				</view>
				<view class="acname_r">
					{{ singupinfo.name }}
					<text v-if="allForm.length>1">({{ formLength.length < allForm.length ? formLength.length +'-'+ allForm.length : allForm.length }}人)</text>
				</view>
			</view>
			<view class="acprice">
				<view class="acprice_l">
					项目费用
				</view>
				<view class="acprice_r">
					{{ singup_money > 0?'￥'+singup_money:'免费' }}
				</view>
			</view>
		</view>
		<view class="form" v-for="(item, index) in form" :key="index">
			<view class="form_title pad">
				<view class="left">
					<text v-if="form.length == 1">报名人信息</text>
					<text v-else>报名人信息{{ index + 1 }}</text>
				</view>
				<view class="right" v-if="(index+1) > formLength.length" @tap="delectepeople(index)">
					<image src="https://ykp-new.oss-cn-hangzhou.aliyuncs.com/client/other/deletsinguppeople.png" mode=""></image>
					删除
				</view>
			</view>
			<view :class="['form_info', items.type == 'textarea' ? 'form_info_text':''] " v-for="(items, key) in item.data" :key="key">
				<view class="form_info_l ">
					{{ items.name }}
					<i class="icon" v-if="items.not_null">&#xe83d;</i>
				</view>
				<view class="form_info_r">
					<input type="text" 
					placeholder-style="color:#999999;font-size:28upx" 
					v-if="items.type == 'text' && items.name != '城市' && items.name != '国籍' && items.name != '手机号' "
					 @blur="verify(items)"
					v-model="items.value" 
					:placeholder="'请输入您的' + items.name" />
					<input type="number"
					placeholder-style="color:#999999;font-size:28upx" 
					v-if="items.type == 'text' && items.name == '手机号'"
					 @blur="verify(items)"
					v-model="items.value" 
					:placeholder="'请输入您的' + items.name" />
					<input type="number"  
					@blur="verify(items)" 
					placeholder-style="color:#999999;font-size:28upx" 
					:placeholder="'请输入您的' + items.name" 
					v-model="items.value" 
					v-if="items.type == 'number'" />
					<view class="choose_date" v-else-if="items.name == '性别'"  >
						<input 
						type="text" disabled="true" 
						v-model="items.value"
						:placeholder="'请选择您的'+items.name"
						placeholder-style="color:#999999;font-size:28upx" />
						<i class="icon">&#xe649;</i>
						<picker :range="items.data_sex" range-key="label" @change="changesex($event,index,key)" class="pick" >
						</picker>
					</view>
					<!-- 出生日期 -->
					<view class="choose_date" v-else-if="items.type == 'date'"  >
						<input 
						type="text" disabled="true" 
						v-model="items.value"
						placeholder="请选择您的出生日期"
						placeholder-style="color:#999999;font-size:28upx" />
						<i class="icon">&#xe649;</i>
						<picker class="pick" mode="date" 
						  :start="items.start_date ? items.start_date : startDate"
						  :end=" items.end_date ? items.end_date : endDate " @change="pickchange($event,index,key)"  >
						</picker>
					</view>
					<view class="choose_date" v-else-if="items.type == 'select'"  >
						<input 
						type="text" disabled="true" 
						v-model="items.value"
						:placeholder="'请选择您的'+items.name"
						placeholder-style="color:#999999;font-size:28upx" />
						<i class="icon">&#xe649;</i>
						<picker :range="items.data" range-key="label" @change="changecard($event,index,key)" class="pick" >
						</picker>
					</view>
					<!-- 选择国家 -->
					<view class="choose_date" v-else-if="items.name == '国籍'"  @tap="choosearea(index,key)">
						<input 
						type="text" disabled="true" 
						v-model="items.value"
						placeholder="请选择您的国家"
						placeholder-style="color:#999999;font-size:28upx" />
						<i class="icon">&#xe649;</i>
						<picker :range="country_C" @change="changecountry($event,index,key)" class="pick" >
						</picker>
					</view>
					<!-- 选择城市 -->
					<view class="choose_date" v-else-if="items.name == '城市'"  @tap="choosearea(index,key)">
						<input 
						type="text" disabled="true" 
						v-model="items.city"
						placeholder="请选择您所在的城市"
						placeholder-style="color:#999999;font-size:28upx" />
						<i  class="icon">&#xe649;</i>
					</view>
					<!-- 多行文本 -->
					<textarea auto-height="true" 
					v-model="items.value" class="te_area" 
					placeholder-style="color:#999999;font-size:28upx"  
					:placeholder="'请输入您的'+items.name" 
					v-if="items.type == 'textarea'" />
					<!-- 上传照片 -->
					<view class="up_img" v-if="items.type == 'image'" @tap="upimg(index,key)">
						<image v-if="items.value" :src="items.value" mode="aspectFill"></image>
						<image v-else src="../../static/img/singup_upimg.png" mode=""></image>
					</view>
				</view>
			</view>
		</view>
		<!-- 添加报名人-->
		<!-- v-if="formLength.length < allForm.length" -->
		<view class="addpeople" v-if="formLength.length < allForm.length 
		&& form.length< allForm.length " @tap="addsingpeople">
			<image src="https://ykp-new.oss-cn-hangzhou.aliyuncs.com/client/other/addsingupeople.png" mode=""></image>
			添加报名人
		</view>
		<view class="addpeople" v-else-if="singupinfo.is_replace" @tap="addsingpeopleT">
			<image src="https://ykp-new.oss-cn-hangzhou.aliyuncs.com/client/other/addsingupeople.png" mode=""></image>
			添加报名人
		</view>
		<!-- 附加服务信息 -->
		<!-- 附加服务 -->
		<view class="singup_item" v-if="servicelist.length">附加服务</view>
		<view class="service">
			<view class="service_service" v-for="(item, index) in servicelist" :key="index">
				<view class="service_choose_click" @tap="choose_change(index)">
					<view :class="['service_choose', item.flag == true ? 'service_choose_item' : '']" >
						<image v-if="item.flag" src="https://ykp-new.oss-cn-hangzhou.aliyuncs.com/client/index/sinup_true.png" mode=""></image>
					</view>
				</view>
				<view class="service_contant">
					<view class="service_contant_t">
						<view class="title">{{ item.name }}</view>
						<!-- 选择数量 -->
						<view class="choose_number" v-if="item.flag">
							<view class="choose_number_one" @tap="changeservicenum(index)"><i class="icon">&#xe618;</i></view>
							<view class="choose_number_two">{{ item.ser_num }}</view>
							<view class="choose_number_one" @tap="changeservicenum_add(index)"><i class="icon">&#xe626;</i></view>
						</view>
					</view>
					<view class="service_contant_b" @tap="showservice(index)">
						该服务包含：{{ item.memo }}...
						<text>【查看更多+】</text>
					</view>
					<view class="price">￥{{ item.price * item.ser_num }}</view>
				</view>
			</view>
		</view>
		<view class="submit_top">
			<i :class="['icon', agreeiconflag ? 'icon_true' : '']" @tap="agreeiconflag = !agreeiconflag">&#xe63c;</i>
			我同意并阅读
			<text>《一块跑报名协议》</text>
		</view>
		<view class="submit">
			<view :class="['submit_singup', agreeiconflag ? '' : 'submit_singup_n']" @tap="topay">提交报名</view>
		</view>
		<uni-popupt ref="chooseservice" >
			<view class="show_ser_contant">
				<!-- 错误按钮 -->
				<view class="err" 
				 @tap="close_p"><i class="icon">&#xe66f;</i></view>
				<scroll-view scroll-y="true" 
				class="scroll-Y" v-for="(item, index) in servicelist" 
				v-if="serviceIndex == index"
				:key="index">
					<view class="p_ser_title">{{ item.name }}</view>
					<view class="p_ser_contant">
						<view class="" v-html="item.detail"></view>
					</view>
					<!-- <image src="https://ykp-new.oss-cn-hangzhou.aliyuncs.com/client/01.jpeg" mode="widthFix"></image> -->
				</scroll-view>
			</view>
		</uni-popupt>
		<!-- 选择地址 -->
		<w-picker
			mode="region"
			:defaultVal="['安徽省', '合肥市', '包河区']"
			:areaCode="['34', '3401', '340111']"
			:hideArea="true"
			@confirm="onConfirmarea"
			ref="region"
			:timeout="true"
		></w-picker>
	</view>
</template>

<script>
	function getDate(type) {
		const date = new Date();
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();
		if (type === 'start') {
			year = year - 60;
		} else if (type === 'end') {
			year = year + 0;
		}
		month = month > 9 ? month : '0' + month;;
		day = day > 9 ? day : '0' + day;
		return `${year}-${month}-${day}`;
	}
// 引入国家
import country from '@/components/country/country.js'
import wPicker from '@/components/w-picker/w-picker.vue';
import uniPopupt from '@/components/uni-popupt/uni-popup.vue';
import { pathToBase64, base64ToPath } from '@/js_sdk/gsq-image-tools/image-tools';
export default {
	components: { uniPopupt,wPicker },
	data() {
		return {
			startDate:getDate('start'),
			endDate:getDate('end'),
			startDate_f:'',
			startDate_f:'',
			endDate_f:'',
			// 活动信息
			activeinfo: {
				group: '亲子组',
				group_num: '2-3',
				price: '99.00'
			},
			www:[{id:'1'},{id:'2'}],
			// 报名列表
			singuplist: [{ name: '', sex: '', mobile: '', src: '' }, { name: '', sex: '', mobile: '', src: '' }],
			popupflag: false,
			sex: '',
			sexindex: '',
			agreeiconflag: true,
			// 附加服务
			servicelist: [],
			active_id: '',
			id: '',
			form: [], // 初始阶段可以报名的
			addform:[], // 被添加的 代报名
			allForm: [], // 总共可以报名的
			formLength: [], // 判断初始报名人数
			singupinfo: {},
			not_null: false,
			singup_money: 0,
			nowTime: '', //当前时间的时间戳
			team_id: '', // 报名的组别id
			serv_data: [],
			sinup_form: [] ,// 报名信息
			birth_date:''  ,// 出生时间
			serviceIndex:'' ,// 服务下标
			source:1,
			city:'',
			cityIndex:'', //选择城市 给个下标
			cityKey:'',
			country_C:[],
			header_img: '',
			singupPhone:[],
			teampaper_id:'',
			verifyflag:false // 当前组别要不要审核
			
		};
	},
	onLoad(e) {
		// console.log(e)
		this.active_id = e.activeid;
		this.id = e.index;
		this.singup_money = e.price;
		this.teampaper_id = e.teampaper_Id
	},
	mounted() {
		this.getgroupInfo();
		this.getserviceInfo();
		this.nowTime = new Date().getTime();
		this.jude_phone()
		this.country_C = country[0];
		// console.log(this.country_C)
	},
	methods: {
		//  上传图片
		upimg(index,key) {
			uni.chooseImage({
				count: 1, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				success: res => {
					var sys_info = uni.getSystemInfoSync();
					if(sys_info.version) {
						console.log(sys_info.version);
						uni.showLoading({
							title: '图片上传中'
						});
						var arr = res.tempFilePaths[0].split('/');
						var filename = arr[arr.length - 1];
						this.oss_upload(res, filename, {
							success: res => {
								this.form[index].data[key].value = 'https://ykp-new.oss-cn-hangzhou.aliyuncs.com/' + filename;
								uni.hideLoading()
							},
							fail: ress => {}
						});
					} else {
						pathToBase64(res.tempFilePaths[0])
							.then(base64 => {
								console.log(base64,111)
								this.header_img = base64;
								this.img_type = base64.split(';')[0].split('/')[1];
								uni.showLoading({
									title: '图片上传中'
								});
								// 获取图片信息
								//获取文件名称
								var arr = res.tempFilePaths[0].split('/');
								var filename = arr[arr.length - 1];
								var timestamp = new Date().getTime();
								var name = timestamp + '.' + this.img_type;
								this.oss_upload(res, name, {
									success: res => {
										this.form[index].data[key].value = 'https://ykp-new.oss-cn-hangzhou.aliyuncs.com/' + name;
										// this.header_img = filename;
										uni.hideLoading()
									},
									fail: ress => {}
								});
							})
							.catch(error => {
								console.error(error);
							});
					}
				}
			});
		},
		// 判断当前的是小程序还是h5
		jude_phone () {
			const phone_info = uni.getSystemInfoSync();
			if(phone_info.version) {
				this.source = 1
			}else {
				this.source = 3
			}
		},
		verify (items) {
			if(items.name == '手机号' && items.value) {
				// console.log()
				var include = this.singupPhone.indexOf(items.value)
				console.log(include)
				if(include == -1) {
					this.singupPhone.push(items.value)
					console.log(this.singupPhone)
				}else {
					this.toast('报名人的手机号不能相同')
					items.value = ''
					return false
				}
				this.ajax('order/checkMobileUse', {
					data: {
						active_id:this.active_id,
						mobile:items.value
					},
					success: res=> {
						console.log(res)
						if(!res.code) {
							this.toast(res.msg)
							this.singupPhone.pop(items.value)
							items.value =''
							return false
						}
						// console.log(res)
					}
				})
			}
			
			 if(items.name == '手机号' && items.value || items.name == '紧急联系方式' && items.value) {
				   if(!items.value) {
					   this.toast('请输入手机号')
				   }else if(!(/^1[3456789]\d{9}$/.test(items.value))){ 
						this.toast('手机号位数不对，请输入正确的手机号')
						items.value = ''
				        return false; 
				    } 
			}else if (items.name == '邮箱' && items.value) {
				if(!(/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(items.value))){
					this.toast('邮箱有误，请输入正确的邮箱')
					items.value = ''
				     return false; 
				 } 
			}else if ( items.name == '证件号' &&items.value) {
				var reg=/^(^[1-9]\d{5}[1-9]\d{3}(((0[2])([0|1|2][0-8])|(([0-1][1|4|6|9])([0|1|2][0-9]|[3][0]))|(((0[1|3|5|7|8])|(1[0|2]))(([0|1|2]\d)|3[0-1]))))((\d{4})|\d{3}[Xx])$)$/;
				if(!(reg.test(items.value))){
					this.toast('证件号有误，请输入正确的证件号')
					items.value = ''
				     return false; 
				 } 
			}
		},
		// 选择性别
		radiochange(ee,index,key) {
			console.log(e);
			this.sex = e.target.value;
			this.form[index].data[key].value = e.target.value;
		},
		// 选择日期
		pickchange (e,index,key) {
			this.birth_date = e.target.value
			// item.value = this.birth_date;
			this.form[index].data[key].value = e.target.value;
			this.$forceUpdate();
			console.log(this.birth_date);
			
		},
		// 选择城市
		choosearea(index,key) {
			this.cityIndex = index
			this.cityKey= key
			// console.log(this.form[index].data[key].value)
			// this.form[index].data[key].value =this.city
			this.$refs.region.show();
		},
		onConfirmarea(e) {
			// this.city = e.result
			this.form[this.cityIndex].data[this.cityKey].city =e.checkArr[1]
			this.form[this.cityIndex].data[this.cityKey].value =e.checkArr[0]+'/'+e.checkArr[1]
			console.log(e)
		},
		// 选择证件类型
		changecard (e,index,key) {
			console.log(e)
			this.form[index].data[key].value = this.form[index].data[key].data[e.target.value].label
		},
		changecountry (e,index,key) {
			console.log(e.target.value)
			this.form[index].data[key].value = this.country_C[e.target.value]
		},
		changesex (e,index,key) {
			console.log(e)
			this.form[index].data[key].value = this.form[index].data[key].data_sex[e.target.value].label
		},
		// 获取服务信息
		getserviceInfo() {
			this.ajax('active/activeService', {
				data: {
					active_id: this.active_id
				},
				success: res => {
					res.msg.forEach(item => {
						item.flag = false;
						item.ser_num = 1;
						item.memo = item.memo.slice(0,30)
					});
					this.servicelist = res.msg;
				}
			});
		},
		// 时间戳转为时间
			get_D (dt) {
				dt = new Date(dt);
				let year = dt.getFullYear();
				let month = dt.getMonth() + 1;
				let day = dt.getDate();
				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return  `${year}-${month}-${day}`;
			},
		// 获取组别信息
		getgroupInfo() {
			const that = this;
			this.ajax('active/activeTeam', {
				data: {
					active_id: this.active_id
				},
				success: res => {
					// console.log(res)
					// console.log(res.msg[that.id].form )
					const gro = res.msg[that.id].form;
					// console.log(gro )
					gro.forEach(e => {
						// console.log(e)
						const val = e.data;
						val.forEach(item => {
							item.city=''
							item.value = '';
							if (item.limit == 1 && item.name == '性别') {
								item.data_sex = [{ label: '男', value: '0' }];
								item.value = '男'
							} else if (item.limit == 2 && item.name == '性别') {
								item.data_sex = [{ label: '女', value: '0' }];
								item.value = '女'
							} else {
								item.data_sex = [{ label: '男', value: '0' }, { label: '女', value: '1' }];
							}
							// 将时间限制 的时间戳转为时间模式
							if( item.name == '生日' && item.limit) {
								item.start_date = this.get_D(item.data[0])
								item.end_date = this.get_D(item.data[1])
							}
						});
						if (e.not_null) {
							// 初始报名人数
							that.form = that.form.concat(e);
							that.formLength = that.formLength.concat(e);
						}
					});
					that.singupinfo = res.msg[that.id];
					// 设置代报名的初始表格
					if(res.msg[that.id].is_replace) {
						that.addform = JSON.parse(JSON.stringify(res.msg[that.id].form[0]))
						// console.log(res.msg[that.id].form)
					}
					that.team_id = res.msg[that.id].id;
					console.log(res)
					that.verifyflag =  res.msg[that.id].is_verify
					that.allForm = res.msg[that.id].form;
					// this.form = res.msg[this.id].form
					// console.log(this.form)
					// this.not_null = res.msg[0].form.not_null;
				}
			});
		},
		// 选择服务
		choose_change(key) {
			this.servicelist[key].flag = !this.servicelist[key].flag;
			if(!this.servicelist[key].flag ) {
				this.servicelist[key].ser_num = 1
			}
		},
		changeservicenum(key) {
			if (this.servicelist[key].ser_num == 1) return;
			this.servicelist[key].ser_num--;
			// console.log(this.serv_data);
		},
		changeservicenum_add(key) {
			if (this.servicelist[key].ser_num == this.servicelist[key].num) return;
			this.servicelist[key].ser_num++;
			// console.log(this.serv_data);
		},
		// 关闭服务弹窗
		close_p() {
			// console.log(key)
			this.$refs.chooseservice.close();
		},
		// 开启服务弹窗
		showservice(key) {
			// console.log(key)
			this.serviceIndex = key
			this.$refs.chooseservice.open();
		},
	
		bindPickerChange(e) {
			// console.log(e.target.value);
			this.singuplist[this.sexindex].sex = this.sex[e.target.value];
		},
		// 代报名添加报名人
		addsingpeopleT () {
			this.addform = JSON.parse(JSON.stringify(this.addform))
			this.addform.data.forEach( (item) => {
				// console.log(item)
				item.value=''
			})
			// console.log(this.addform)
			// console.log(11)
			this.form = this.form.concat(this.addform)
		},
		// 添加报名人
		addsingpeople() {
			// if(this.form.length == this.allForm.length) {
			// 	this.toast('最多只能报名'+this.allForm.length+'人')
			// 	return
			// }
			// this.singuplist.push({
			// 	name:'',mobile:'',nickname:''
			// })
			// console.log(this.allForm[this.form.length].not_null)
			// this.form = this.form.concat(this.form.slice(0, 1));
			this.allForm[this.form.length].not_null = true
			this.form =this.form.concat(this.allForm[this.form.length])
			// this.$forceUpdate()
			// console.log(this.allForm[this.form.length].not_null)
		},
		// 删除报名人
		delectepeople(key) {
			uni.showLoading({
				title: '删除中'
			});
			var that = this;
			setTimeout(function() {
				uni.hideLoading();
				that.form.splice(key, 1);
			}, 1000);
		},
	
		topay() {
			if (!this.agreeiconflag) {
				this.toast('请勾选报名协议');
				return;
			}
			uni.showToast({
				mask: true,
				icon: 'loading',
				title: '提交报名中',
				duration: 2000
			});
			const _this = this;
			_this.sinup_form = [];
			var dt = this.servicelist;
			dt.forEach(item => {
				var ser = {};
				if (item.flag) {
					(ser.id = item.id), (ser.num = item.ser_num);
					_this.serv_data = _this.serv_data.concat(ser);
				}
			});
			// 去掉表单中的notnull
			var newform = _this.form;
			// console.log(newform);
			newform.forEach(e => {
				console.log(e)
				// delete e.not_null
			_this.sinup_form.push(e.data)
			});
			this.submit_pay();
		},
		// 提交报名
		submit_pay() {
			console.log( this.sinup_form)
			this.sinup_form.forEach( (item) => {
				if(item.not_null && item.name == '手机号') {
					if(!(/^1[3456789]\d{9}$/.test(item.value))){
						this.toast('手机号位数不对，请输入正确的手机号')
					    return false; 
					 } 
				}
			})
			this.ajax('Orderadd/addOrder', {
				data: {
					form: this.sinup_form,
					active_id: this.active_id,
					team_id: this.team_id,
					serv_data: this.serv_data,
					source: '3',
					teampaper_id:this.teampaper_id
				},
				success: res => {
					console.log(res);
					if (res.code && res.msg.total_price) {
						uni.navigateTo({
							url: '/pages/index/pay?id='+res.msg.id+'&activename='+res.msg.active_name+'&verify='+this.verifyflag
						});
					}else if (res.code && !res.msg.total_price){
						uni.navigateTo({
							url:'/pages/index/paysuccess?price='+'0'
						})
					} else {
						this.toast(res.msg);
					}
				}
			});
		}
	}
};
</script>
<style>
page {
	background-color: #ffffff;
}
</style>
<style lang="less" scoped>
@import url('../../static/less/message.less');
</style>
